package dao

import (
	"os"

	"gitee.com/xuesongtao/collect/library/pushlog"

	pslog "gitee.com/xuesongtao/ps-log"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
)

type ToDingDing struct {
	initd bool
	ddObj *pushlog.DingDing
}

func (t *ToDingDing) init() {
	if t.initd {
		return
	}
	t.initd = true
	t.ddObj = pushlog.NewDingDing(5, g.Cfg().GetString("pusherrlog.push_dingding_url"))
}

func (t *ToDingDing) WriteTo(bus *pslog.LogHandlerBus) {
	projectName, appName := ParsePath(bus.Ext)

	// 判断是否在允许的推送时间段, 不是的话就需要存入延迟推送文件
	if ok := DelayPushObj.NeedDelay(); ok {
		fh, err := FilePool.Get(DelayPushObj.GetDelayFileName(DelayPushErr), os.O_APPEND)
		if err != nil {
			glog.Error("filePool.Get is failed, err:", err)
			return
		}
		defer FilePool.Put(fh)

		chunk := DelayPushObj.GetSaveDelayChunk(projectName, appName, bus.Msg)
		_, err = fh.AppendContent(chunk)
		if err != nil {
			glog.Error("append file is failed, err:", err)
			return
		}
		glog.Info("it is have write delay file")
		if !DelayPushObj.getDelay() {
			DelayPushObj.setDelay(true)
		}
		return
	}

	// 判断下是否存在延迟的推送的内容
	if DelayPushObj.getDelay() {
		if DelayPushObj.setDelay(false) { // 防止 data race
			pushErrLog := DelayPushObj.GetDelayFileName(DelayPushErr)
			fh, err := FilePool.Get(pushErrLog, os.O_RDWR)
			if err != nil {
				glog.Error("filePool.Get is failed, err:", err)
				return
			}
			defer FilePool.Put(fh)

			f := fh.GetFile()
			DelayPushObj.StartPushFile(f, t)

			// 清空文件
			fh.Clean()
		}
	}

	t.inTo(projectName, appName, bus.Msg)
}

func (t *ToDingDing) inTo(projectName, appName, msg string) {
	t.init()
	title := pushlog.GetPushLogTitle(projectName, appName)

	// 发生钉钉
	if resp, err := t.ddObj.PushText(pushlog.ErrLogType, title, msg); err != nil {
		glog.Error("CjDingDing push is failed, respBody: %s, err: %v", string(resp.Body), err)
	}
}
